import {SET_ROUTERS} from '../mutations'
import moduleRouter from '@/router/module_router'
// 根据路由名称获取菜单
function getMenu (name, menus) {
  if (menus && menus.length > 0) {
    for (let i = 0; i < menus.length; i++) {
      let menu = menus[i]
      if (name === menu.viewName) {
        return menu
      }
    }
  }
  return null
}
// 设置菜单路由
const hasPermission = function (menus, route) {
  if (route.name && route.name !== null) {
    let currMenu = getMenu(route.name, menus)
    if (currMenu !== null) {
      if (currMenu.hidden !== null) {
        route.hidden = currMenu.hidden !== 1
      }
      if (route.hidden) {
        return false
      }
      // 设置菜单的标题、图标和可见性
      if (currMenu.menuName !== null && currMenu.menuName !== '') {
        route.meta.title = currMenu.menuName
      }
      if (currMenu.menuIcon !== null && currMenu.menuIcon !== '') {
        route.meta.icon = currMenu.menuIcon
      }
      if (currMenu.sort !== null && currMenu.sort !== '') {
        route.sort = currMenu.sort
      }
      return true
    } else {
      route.sort = 0
      if (route.hidden !== undefined && route.hidden === true) {
        route.sort = -1
        return true
      } else {
        return false
      }
    }
  } else {
    return true
  }
}
// 过滤路由
const filterRouter = function (menus) {
  const moduleRouterMap = {}
  const rootModule = menus.root || []
  sortModule(rootModule)
  moduleRouterMap.root = rootModule
  let addRouters = []
  let rootRouterPath = ''
  if (rootModule && rootModule.length > 0) {
    for (let index = 0; index < rootModule.length; index++) {
      const module = rootModule[index].viewName
      const moduleRouters = moduleRouter.getModuleRouter(module)
      if (!moduleRouters || moduleRouters === null) {
        continue
      }
      const menuList = menus[module]
      const accessRouters = filterModuleRouter(moduleRouters, menuList)
      if (accessRouters && accessRouters.length <= 0) {
        continue
      }
      sortRouters(accessRouters)
      const defaultActiveRouter = getModuleActiveDefaultRouter(accessRouters, module)
      //  设置每个模块默认的导航路由
      if (defaultActiveRouter) {
        if (rootRouterPath === undefined || rootRouterPath === '') {
          rootRouterPath = defaultActiveRouter.redirect
        }
        accessRouters.push(defaultActiveRouter)
      }
      moduleRouterMap[module] = accessRouters
      addRouters = addRouters.concat(accessRouters)
    }
  }
  // 顶层路由
  addRouters.push({
    path: '/',
    redirect: rootRouterPath || '/weclome',
    hidden: true
  })
  moduleRouterMap.addAll = addRouters
  return moduleRouterMap
}

function getModuleActiveDefaultRouter (accessRouters, module) {
  if (accessRouters && accessRouters.length > 0) {
    const firstRouter = accessRouters[0]
    if (firstRouter.children && firstRouter.children.length > 0) {
      const firstChild = firstRouter.children[0]
      const childPath = firstChild.meta ? firstChild.meta.redirect || firstChild.path : firstChild.path
      firstRouter.redirect = firstRouter.path + '/' + childPath
    }
    return {
      path: `/${module}`,
      name: module,
      redirect: firstRouter.redirect,
      hidden: true
    }
  }
  return null
}
// 过滤路由
function filterModuleRouter (moduleRouters, menus) {
  return moduleRouters.filter(v => {
    if (hasPermission(menus, v)) {
      if (v.children && v.children.length > 0) {
        v.children = v.children.filter(child => {
          if (hasPermission(menus, child)) {
            return child
          }
          return false
        })
        return v.children && v.children.length > 0 ? v : false
      } else {
        if (v.name && v.name !== null) {
          return v
        }
        return false
      }
    }
    return false
  })
}

// 对模块进行排序
function sortModule (rootModule) {
  rootModule.sort(compare('sort'))
}

// 对菜单进行排序
function sortRouters (accessedRouters) {
  for (let i = 0; i < accessedRouters.length; i++) {
    let router = accessedRouters[i]
    if (router.children && router.children.length > 0) {
      router.children.sort(compare('sort'))
    }
  }
  accessedRouters.sort(compare('sort'))
}

// 升序比较函数
function compare (p) {
  return function (m, n) {
    let a = m[p]
    let b = n[p]
    return a - b
  }
}

const permission = {
  namespaced: true,
  state: {
    crmRouters: [],
    systemRouters: [],
    eimsRouters: [],
    addRouters: []
  },
  mutations: {
    [SET_ROUTERS]: (state, data) => {
      state.crmRouters = (data && data.crm) || []
      state.systemRouters = (data && data.system) || []
      state.eimsRouters = (data && data.eims) || []
      state.addRouters = (data && data.addAll) || []
    }
  },
  actions: {
    // 生成可访问路由
    GenerateAccessRouters ({commit}, menus) {
      return new Promise((resolve, reject) => {
        const accessedRouters = filterRouter(menus)
        commit(SET_ROUTERS, accessedRouters)
        resolve()
      })
    }
  }
}
export default permission
